#!/bin/bash
##Script for prallel watershed creating with grass
## John Talbot, October 2015

##	To run :
##	start GRASS70
##	parallelGrass.sh <number of cores> <Master Pointfile> <direction rasterFile> <output directory>

##Setup

number_of_cores=$1
pointFile=$2
number_of_cores=$(($number_of_cores-1))
jobString=""

echo
echo "CORES:" $(($number_of_cores + 1))
echo "Point File: " $pointFile
echo
echo "Splitting point file"
python fileMaker.py $pointFile $(($number_of_cores+1)) $(pwd)"/"
echo
echo "Writing jobs"
echo 

##Loop to create X number of job scripts
for i in `seq 0 $number_of_cores`; do
echo item: $i
echo "
#!/bin/bash
#parameter <points>

while IFS=',' read -r fid x y name region|| [[ -n \"\$line\" ]]; do
	int="intermediate"\$name
	#echo X: \$x
	#echo Y: \$y
        #echo Name: \$name
	#echo Region: \$region 
	#echo Direction: \$direction
	#echo Intermediate: \$int
	r.water.outlet input=a1_dir  output=\$int coordinates=\$x,\$y --quiet
        r.to.vect input=\$int output=poly_\$name feature=area --quiet
        v.out.ogr input=poly_\$name type=area output=out_\$name.shp --quiet
        g.remove -f type=vector name=poly_\$name --quiet
        g.remove -f type=raster name=\$int --quiet
done < \"segment_$i\" 

echo done job$i
date"> job$i.sh



jobString+=" job$i.sh"

done


##Parallel process job scripts with GNUs parallel program
echo $jobString
echo "run"
echo parallel bash ::: $jobString
